package com.ubxtech.core.utils;

import cn.hutool.core.util.RandomUtil;
import com.ubxtech.core.context.ContextConstants;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Victor.Xiao
 * @since 2021-12-15 19:35
 **/
@Slf4j
public class SignUtil {

    public static String getSignV2(String mAppKey,String deviceId){
        long now = System.currentTimeMillis() / 1000;
        String randStr = RandomUtil.randomString(10);
        // 规则：
        // 1. 计算当前时间戳（单位：秒）拼接 AppKey 和 1-10 位大小写字母和数字随机字符 和终端设备号 X-UBT-DeviceId 生成字符串的 MD5 值，得到签名段.
        // 2. 将签名段与先前的时间戳使用空格连接，同时使用空格连接 randStr 字符串，得到 最终 X-UBT-Sign 内容.
        String sign = Md5Util.md5(now + mAppKey + randStr + deviceId)
                + ContextConstants.SIGN_PART_SEPARATOR + now
                + ContextConstants.SIGN_PART_SEPARATOR + randStr
                + ContextConstants.SIGN_PART_SEPARATOR + ContextConstants.SIGN_VERSION_NUM;
//        System.out.println("---------------------sign: " + sign + " ----------------------");
        return sign;
    }

    public static Map<String, String> createHeaders(String appId, String appKey, String deviceId) {
        Map<String, String> headers = new HashMap<>(3);
        headers.put(ContextConstants.HEADER_APP_ID, appId);
        headers.put(ContextConstants.HEADER_DEVICE_ID, deviceId);
        headers.put(ContextConstants.HEADER_SIGN, getSignV2(appKey, deviceId));
        return headers;
    }

    public static Map<String, Object> createParams(String sn, String domain, String productName) {
        Map<String, Object> queries = new HashMap<>();
        queries.put(ContextConstants.PARAM_SN, sn);
        queries.put(ContextConstants.PARAM_DOMAIN, domain);
        queries.put(ContextConstants.PARAM_PRODUCT_NAME, productName);

        return queries;
    }

}
